import axios from 'axios';
import type { AxiosInstance, AxiosResponse } from 'axios';
import type { RuleConfig, RuleListParams, ApiResponse } from '../types/rule';
import { mockApi } from './mock';

// 创建axios实例
const api: AxiosInstance = axios.create({
  baseURL: '/api/v1',
  timeout: 30000,
  headers: {
    'Content-Type': 'application/json',
  },
});

// 请求拦截器
api.interceptors.request.use(
  (config) => {
    // 添加认证token
    const token = localStorage.getItem('token');
    if (token) {
      config.headers.Authorization = `Bearer ${token}`;
    }
    return config;
  },
  (error) => {
    return Promise.reject(error);
  }
);

// 响应拦截器
api.interceptors.response.use(
  (response: AxiosResponse<ApiResponse<any>>) => {
    const { data } = response;
    if (data.code === 200) {
      return response;
    } else {
      // 统一错误处理
      console.error('API Error:', data.message);
      return Promise.reject(new Error(data.message));
    }
  },
  (error) => {
    if (error.response?.status === 401) {
      // 未授权，跳转到登录页
      localStorage.removeItem('token');
      window.location.href = '/login';
    }
    return Promise.reject(error);
  }
);

// 规则相关API
export const ruleApi = {
  // 获取规则列表
  getRuleList: (params: RuleListParams) => {
    return mockApi.getRuleList(params).then(data => ({
      data: {
        code: 200,
        message: 'success',
        data,
        success: true,
      },
    }));
  },

  // 获取规则详情
  getRuleDetail: (id: string) => {
    return mockApi.getRuleDetail(id).then(data => ({
      data: {
        code: 200,
        message: 'success',
        data,
        success: true,
      },
    }));
  },

  // 创建规则
  createRule: (rule: RuleConfig) => {
    return mockApi.createRule(rule).then(data => ({
      data: {
        code: 200,
        message: 'success',
        data,
        success: true,
      },
    }));
  },

  // 更新规则
  updateRule: (id: string, rule: RuleConfig) => {
    return mockApi.updateRule(id, rule).then(data => ({
      data: {
        code: 200,
        message: 'success',
        data,
        success: true,
      },
    }));
  },

  // 删除规则
  deleteRule: (id: string) => {
    return mockApi.deleteRule(id).then(() => ({
      data: {
        code: 200,
        message: 'success',
        data: null,
        success: true,
      },
    }));
  },

  // 更新规则状态
  updateRuleStatus: (id: string, status: 'active' | 'disabled') => {
    return mockApi.updateRuleStatus(id, status).then(data => ({
      data: {
        code: 200,
        message: 'success',
        data,
        success: true,
      },
    }));
  },

  // 预览规则
  previewRule: (rule: RuleConfig) => {
    return mockApi.previewRule(rule).then(data => ({
      data: {
        code: 200,
        message: 'success',
        data,
        success: true,
      },
    }));
  },

  // 获取数据表列表
  getTableList: () => {
    return mockApi.getTableList().then(data => ({
      data: {
        code: 200,
        message: 'success',
        data,
        success: true,
      },
    }));
  },

  // 获取表字段信息
  getTableFields: (tableName: string) => {
    return mockApi.getTableFields(tableName).then(data => ({
      data: {
        code: 200,
        message: 'success',
        data,
        success: true,
      },
    }));
  },
};

// 结果查询相关API
export const resultApi = {
  // 执行规则查询
  executeRule: (ruleId: string) => {
    return api.post<ApiResponse<any>>(`/results/execute/${ruleId}`);
  },

  // 获取查询结果
  getResultList: (params: any) => {
    return api.get<ApiResponse<any[]>>('/results', { params });
  },

  // 导出结果
  exportResult: (resultId: string, format: 'csv' | 'excel') => {
    return api.get(`/results/export/${resultId}`, {
      params: { format },
      responseType: 'blob',
    });
  },
};

// 日志查询相关API
export const logApi = {
  // 获取操作日志
  getOperationLogs: (params: any) => {
    return api.get<ApiResponse<any[]>>('/logs/operation', { params });
  },

  // 获取执行日志
  getExecutionLogs: (params: any) => {
    return api.get<ApiResponse<any[]>>('/logs/execution', { params });
  },
};

export default api;